<template>
  <!-- 搜索及操作区域 -->
  <x-search>
    <template #search>
      <a-input
        v-model:value="room_id"
        placeholder="请输入房间号"
        style="width: 150px"
      />
      <a-input
        v-model:value="building_id"
        placeholder="请输入楼栋号"
        style="width: 150px; margin-left: 10px"
      />
      <a-select
        v-model:value="type"
        placeholder="查询宿舍类型"
        style="width: 150px; margin-left: 10px"
      >
        <a-select-option
          v-for="(item, index) in all_type"
          :key="index"
          :value="item"
        >
          {{ item }}
        </a-select-option>
      </a-select>

      <a-select
        v-model:value="program_id"
        placeholder="查询专业"
        style="width: 150px; margin-left: 10px"
        @change="proToclass"
      >
        <a-select-option
          v-for="(item, index) in all_programs"
          :key="index"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-select
        v-model:value="class_id"
        placeholder="查询班级"
        style="width: 150px; margin-left: 10px"
      >
        <a-select-option
          v-for="(item, index) in all_classes"
          :key="index"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-button type="primary" style="margin-left: 10px" @click="search_data">
        搜索
      </a-button>
      <a-button style="margin-left: 10px" @click="resetSearch"> 重置 </a-button>
    </template>

    <template #operate>
      <a-button
        type="primary"
        @click="showAddDrawer"
        style="margin-right: 10px"
        v-checkpermission:foo.bar="'housekeep_info_add'"
      >
        <template #icon><plus-outlined style="margin-right: 0" /></template>
        新建宿舍
      </a-button>
      <a-button style="background: #67c23a; color: #ffffff; width: 80px">
        <template #icon>
          <DownloadOutlined style="margin-right: 0" />
        </template>
        导出
      </a-button>
    </template>
  </x-search>

  <!-- 表格数据 -->
  <a-table
    :columns="columns"
    :data-source="dataSource"
    :pagination="pagination"
    :loading="loading"
    @change="handleTableChange"
    style="margin-top: 20px"
    v-checkpermission:foo.bar="'housekeep_info_list'"
  >
    <!-- 统一使用 bodyCell 处理所有自定义列 -->
    <template #bodyCell="{ column, record }">
      <!-- 状态列 -->
      <template v-if="column.key === 'state_del'">
        <a-tag :color="record.state_del === 0 ? 'green' : 'red'">
          {{ record.state_del === 0 ? "启用" : "禁用" }}
        </a-tag>
      </template>

      <!-- 宿舍类型列 -->
      <template v-else-if="column.key === 'type'">
        <a-tag :color="record.type === '男生宿舍' ? 'blue' : 'pink'">
          {{ record.type }}
        </a-tag>
      </template>

      <!-- 操作列 -->
      <template v-else-if="column.key === 'action'">
        <div class="action-buttons">
          <!-- 编辑按钮 -->
          <a-tooltip title="编辑">
            <a-button
              type="text"
              size="small"
              class="action-btn edit-btn"
              @click="showEditDrawer(record)"
              v-checkpermission:foo.bar="'housekeep_info_edit'"
            >
              <EditOutlined />
            </a-button>
          </a-tooltip>

          <!-- 状态切换按钮 -->
          <a-tooltip :title="record.state_del === 1 ? '启用' : '禁用'">
            <a-button
              type="text"
              size="small"
              :class="['action-btn', record.state_del === 1 ? 'enable-btn' : 'disable-btn']"
              @click="record.state_del === 1 ? handleStart(record) : handleDelete_f(record)"
              v-checkpermission:foo.bar="'housekeep_delete'"
            >
              <component :is="record.state_del === 1 ? CheckCircleOutlined : StopOutlined" />
            </a-button>
          </a-tooltip>

          <!-- 删除按钮 -->
          <a-tooltip title="删除" v-if="record.state_del === 1">
            <a-button
              type="text"
              size="small"
              class="action-btn delete-btn"
              @click="handleDelete(record)"
              v-checkpermission:foo.bar="'housekeep_delete'"
            >
              <DeleteOutlined />
            </a-button>
          </a-tooltip>

          <!-- 详情按钮 -->
          <a-tooltip title="详情">
            <a-button
              type="text"
              size="small"
              class="action-btn detail-btn"
              @click="hostelView(record)"
              v-checkpermission:foo.bar="'housekeep_info_list'"
            >
              <EyeOutlined />
            </a-button>
          </a-tooltip>

          <!-- 成员管理按钮 -->
          <a-tooltip title="成员管理">
            <a-button
              type="text"
              size="small"
              class="action-btn manage-btn"
              @click="manage(record)"
              v-checkpermission:foo.bar="'housekeep_info_management'"
            >
              <TeamOutlined />
            </a-button>
          </a-tooltip>
        </div>
      </template>
    </template>
  </a-table>

  <!-- 新增/编辑抽屉 -->
  <a-drawer
    v-model:open="drawerVisible"
    :title="currentAction === 'add' ? '新建宿舍记录' : '编辑宿舍记录'"
    width="500"
  >
    <!-- 添加 ref 和 rules -->
    <a-form
      ref="formRef"
      :model="currentHostel"
      :rules="formRules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-form-item label="宿舍楼栋号" name="building_id">
        <a-input
          v-model:value="currentHostel.building_id"
          placeholder="请输入宿舍楼栋号"
        />
      </a-form-item>
      <a-form-item label="宿舍房间号" name="room_id">
        <a-input
          v-model:value="currentHostel.room_id"
          placeholder="请输入宿舍房间号"
        />
      </a-form-item>
      <a-form-item label="宿舍类型" name="type">
        <a-select
          v-model:value="currentHostel.type"
          placeholder="请选择宿舍类型"
        >
          <a-select-option
            v-for="(item, index) in all_type"
            :key="index"
            :value="item"
          >
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="宿舍班级" name="class_id">
        <a-select
          v-model:value="currentHostel.class_id"
          placeholder="请选择宿舍班级"
          @change="handleStudentSelect"
        >
          <a-select-option
            v-for="(item, index) in all_classes"
            :key="index"
            :value="item.id"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="宿舍专业" name="program_id">
        <a-select
          v-model:value="currentHostel.program_id"
          placeholder="选择班级后自动填写(无需手动)"
          disabled
        >
          <a-select-option
            v-for="(item, index) in all_programs"
            :key="index"
            :value="item.id"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="人数" name="person_number">
        <a-input-number
          v-model:value="currentHostel.person_number"
          :min="0"
          :max="10"
          style="width: 100%"
        />
      </a-form-item>
      <a-form-item label="负责老师" name="teacher">
        <a-select
          placeholder="请选择宿舍负责老师"
          v-model:value="currentHostel.teacher"
          show-search
          :options="teacher_list"
          :filter-option="filterOption"
        ></a-select>
      </a-form-item>
      <a-form-item label="备注信息" name="comment">
        <a-input
          v-model:value="currentHostel.comment"
          placeholder="请输入备注信息"
        />
      </a-form-item>
    </a-form>
    <!-- 添加 footer 插槽 -->
    <template #footer>
      <a-button @click="resetForm">重置</a-button>
      <a-button type="primary" @click="handleSubmit" style="margin-left: 20px"
        >确定</a-button
      >
    </template>
  </a-drawer>

  <!-- 查看宿舍详情的Model -->
  <a-modal
    v-model:visible="open_view"
    title="宿舍详情"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div class="dorm-card">
      <!-- 标题 -->
      <h2 class="header">宿舍详细信息</h2>

      <!-- 主体信息 -->
      <div class="content-wrapper">
        <!-- 左侧信息列 -->
        <div class="left-column">
          <div class="info-row">
            <span class="label">房间号</span>
            <span class="value">{{ view_data.room_id }}</span>
          </div>
          <div class="info-row">
            <span class="label">楼栋号</span>
            <span class="value">{{ view_data.building_id }}</span>
          </div>
          <div class="info-row">
            <span class="label">楼层</span>
            <span class="value">{{ view_data.floor }}</span>
          </div>
          <div class="info-row">
            <span class="label">房间类型</span>
            <span class="value">{{ view_data.type }}</span>
          </div>
          <div class="info-row">
            <span class="label">床位数</span>
            <span class="value">{{ view_data.bedCount }}</span>
          </div>
          <div class="info-row">
            <span class="label">已住人数</span>
            <span class="value">{{ view_data.person_number }}</span>
          </div>
          <div class="info-row">
            <span class="label">空余床位</span>
            <span class="value">{{ view_data.availableBeds }}</span>
          </div>
        </div>

        <!-- 右侧信息列 -->
        <div class="right-column">
          <div class="info-row">
            <span class="label">班级</span>
            <span class="value">{{ view_data.class_name }}</span>
          </div>
          <div class="info-row">
            <span class="label">专业</span>
            <span class="value">{{ view_data.program_name }}</span>
          </div>
          <div class="info-row">
            <span class="label">班主任</span>
            <span class="value">{{ view_data.teacher }}</span>
          </div>
          <div class="info-row">
            <span class="label">联系电话</span>
            <span class="value">{{ view_data.teacher_phone }}</span>
          </div>

          <!-- 备注信息 -->
          <div class="remarks">
            <h3>备注信息</h3>
            <p>{{ view_data.comment || "无" }}</p>
          </div>
        </div>
      </div>
    </div>
  </a-modal>

  <!-- 最后成员管理表 -->
  <a-drawer v-model:open="drawerManage" title="宿舍成员管理" width="800">
    <!-- 上面的描述列表 -->
    <a-descriptions
      title="房间详情"
      :column="{ xxl: 2, xl: 2 }"
      bordered
      :labelStyle="{
        width: '100px',
        backgroundColor: '#fafafa',
        fontWeight: 500,
      }"
    >
      <a-descriptions-item
        v-for="item in detailData"
        :key="item.label"
        :label="item.label"
      >
        {{ item.value }}
      </a-descriptions-item>
    </a-descriptions>
    <!-- 下面的宿舍管理表格 -->
    <a-table
      :columns="columns_M"
      :data-source="dataSource_M"
      :pagination="pagination_M"
      @change="handleTableChange_M"
      style="margin-top: 20px"
      v-checkpermission:foo.bar="'housekeep_info_management_list'"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'student_gender'">
          <a-tag :color="record.student_gender === '男' ? 'blue' : 'pink'">
            {{ record.student_gender }}生
          </a-tag>
        </template>
        <!-- bed_space -->
        <template v-if="column.dataIndex === 'bed_space'">
          <a-tag color="#cccccc"> {{ record.bed_space }}号 </a-tag>
        </template>
        <template v-if="column.dataIndex === 'active'">
          <a-button
            type="link"
            @click="showEditDrawerM(record)"
            style="padding: 4px 6px; color: #52c41a"
            v-checkpermission:foo.bar="'housekeep_info_management_edit'"
          >
            <EditOutlined style="margin-right: 0px" />
            编辑</a-button
          >
          <a-button
            type="link"
            danger
            @click="handleDeleteM(record)"
            style="padding: 4px 6px; color: #ff4d4f"
            v-checkpermission:foo.bar="'housekeep_info_management_delete'"
          >
            <DeleteOutlined style="margin-right: 0px" />
            删除</a-button
          >
        </template>
      </template>
    </a-table>
    <!-- 表格下面的进度条，操作符 -->
    <div class="activeAdd">
      <div>
        <span>当前人数：</span>
        <a-progress
          :percent="Number_hostel * 25"
          size="small"
          :format="changeData"
          style="width: 150px"
        />
      </div>
      <a-button
        v-if="Number(Number_hostel) <= 3"
        type="primary"
        @click="showAddDrawer_M"
        v-checkpermission:foo.bar="'housekeep_info_management_add'"
      >
        <template #icon><plus-outlined style="margin-right: 0" /></template>
        新增成员
      </a-button>
      <a-button
        type="primary"
        v-else
        v-checkpermission:foo.bar="'housekeep_info_management_add'"
        disabled
      >
        <template #icon><plus-outlined style="margin-right: 0" /></template>
        新增成员
      </a-button>
    </div>
    <!-- 最下面的操作 -->
    <template #footer>
      <a-space>
        <a-button @click="drawerManage = false">取消</a-button>
        <a-button type="primary" @click="drawerManage = false">确定</a-button>
      </a-space>
    </template>
  </a-drawer>

  <!-- 宿舍中添加学生操作Model -->
  <a-modal
    v-model:visible="open_Add"
    :title="currentAction_M === 'add' ? '添加成员' : '编辑成员'"
    @ok="handleOk_M"
    @cancel="handleCancel_M"
    okText="提交"
  >
    <a-form
      ref="formRefM"
      :model="currentHostelM"
      :rules="formRulesM"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-form-item
        v-if="currentAction_M === 'add'"
        label="学生姓名"
        name="student_idOF"
      >
        <a-select
          v-model:value="currentHostelM.student_idOF"
          placeholder="请选择学生姓名(只显示当前班级)"
          @change="handleStudentSelect_M"
        >
          <a-select-option
            v-for="(item, index) in all_studentList"
            :key="index"
            :value="item.id"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item v-else label="学生姓名" name="student_idOF">
        <a-select
          v-model:value="currentHostelM.student_idOF"
          placeholder="请选择学生姓名(只显示当前班级)"
          @change="handleStudentSelect_M"
        >
          <a-select-option
            v-for="(item, index) in all_studentList"
            :key="index"
            :value="item.id"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="学生学号" name="student_id">
        <a-input
          v-model:value="currentHostelM.student_id"
          placeholder="选择学生后会自动填写(无需手动)"
          disabled
        />
      </a-form-item>
      <a-form-item label="性别" name="gender">
        <a-radio-group
          name="gender"
          v-model:value="currentHostelM.gender"
          disabled
        >
          <!-- 或者使用标准写法 -->
          <a-radio value="男">男</a-radio>
          <a-radio value="女">女</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="班级" name="class_id">
        <a-select
          v-model:value="currentHostelM.class_id"
          placeholder="选择学生后会自动填写(无需手动)"
          disabled
        >
          <a-select-option
            v-for="(item, index) in all_classes"
            :key="index"
            :value="item.id"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="联系电话" name="phone">
        <a-input
          v-model:value="currentHostelM.phone"
          placeholder="选择学生后会自动填写(无需手动)"
          disabled
        />
      </a-form-item>
      <a-form-item label="床位号" name="bed_space">
        <a-input-number
          v-model:value="currentHostelM.bed_space"
          :min="0"
          :max="4"
          style="width: 100%"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { message, Modal } from "ant-design-vue";
import {
  EditOutlined, // 编辑图标
  UploadOutlined, // 上传图标
  EyeOutlined, // 预览图标
  DeleteOutlined, // 删除图标
  FormOutlined, // 批改图标
  PlusOutlined,
  DownloadOutlined,
} from "@ant-design/icons-vue";
import {
  CheckCircleOutlined,
  StopOutlined,
  TeamOutlined,
} from "@ant-design/icons-vue";
import dayjs from "dayjs";
import http from "../routerutils/http";
import BreadCrumb from "./BreadCrumb.vue";
import XCard from "./XCard.vue";
import XSearch from "./XSearch.vue";
import { number } from "echarts";
import { useStore } from "vuex";
const store = useStore();
const userPermiss_vuex = store.state.userPermiss;
// 创建一个自定义指令，来统一处理权限存在与否
const vCheckpermission = {
  mounted: (el: any, binding: any) => {
    if (!userPermiss_vuex.includes(binding.value)) {
      // 移除元素
      el.parentNode?.removeChild(el);
    }
    console.log(el, binding);
    // el.classList.add("is-highlight");
  },
};

// 新增
// 获取老师列表
const teacher_list = ref<object[]>([]);
const get_teacher = async () => {
  try {
    const res = await http.get("/api/users/teacher_list");
    if (res.data.code === 0) {
      teacher_list.value = res.data.results.map((item: any) => {
        return {
          value: item.id,
          label: item.truename,
        };
      });
    }
  } catch (error) {
    console.log("出错了：：:", error);
  }
};
// 老师搜索
const filterOption = (input: string, option: any) => {
  console.log("筛选：：", option);
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

/* 区1：搜索相关操作 */
// 类型定义
interface ClassInfo {
  id?: string;
  name: string;
}

// 加载作业等级数据
const all_type = ref<string[]>(["男生宿舍", "女生宿舍"]);
const all_classes = ref<ClassInfo[]>([]);
const all_programs = ref<ClassInfo[]>([]);
const all_studentList = ref<ClassInfo[]>([]);
// 表单数据
const room_id = ref<number>();
const building_id = ref<number>();
const type = ref<string>();
const class_id = ref<number>();
const program_id = ref<number>();
// 重置搜索表单
const resetSearch = () => {
  pagination.current = 1;
  room_id.value = undefined;
  building_id.value = undefined;
  type.value = undefined;
  class_id.value = undefined;
  program_id.value = undefined;
  search_data();
  loadClasses();
};
// 搜索按钮
const search_data = () => {
  pagination.current = 1; // 重置到第一页
  loadData();
};
// 加载班级数据
const loadClasses = async () => {
  try {
    const res = await http.get("/api/students/allclass");
    all_classes.value = res.data.results;
  } catch (error) {
    message.error("班级数据加载失败");
  }
};

// 加载专业数据
const loadPrograms = async () => {
  try {
    const res = await http.get("/api/students/allprogram");
    all_programs.value = res.data.results;
  } catch (error) {
    message.error("专业数据加载失败");
  }
};

// 根据专业id去获取对应的所以班级
const proToclass = async () => {
  try {
    const response = await http.get("/api/students/pro_class", {
      params: {
        program_id: program_id.value,
      },
    });
    console.log(response.data.results);
    all_classes.value = response.data.results;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};

// 加载学生数据
const loadStudent = async () => {
  try {
    const res = await http.get("/api/attends/allStudent");
    all_studentList.value = res.data.results;
    console.log(res.data.results);
  } catch (error) {
    message.error("专业数据加载失败-学生");
  }
};
onMounted(() => {
  loadClasses();
  loadPrograms();
  loadData();
  loadStudent();
  get_teacher();
});

/* 区2：新建/修改 作业的相关操作 */
const drawerVisible = ref<boolean>(false);
const currentAction = ref<"add" | "edit">("add");
const currentHostel = reactive({
  id: undefined, // 添加ID字段用于编辑
  building_id: "",
  room_id: "",
  type: undefined,
  class_id: undefined,
  program_id: undefined,
  person_number: 0,
  teacher: null,
  comment: "",
});
// 验证规则
const formRules = reactive({
  building_id: [
    { required: true, message: "请输入宿舍楼栋号", trigger: "blur" },
    { pattern: /^\d+$/, message: "只能输入数字", trigger: "blur" },
  ],
  room_id: [
    { required: true, message: "请输入宿舍房间号", trigger: "blur" },
    { pattern: /^\d+$/, message: "只能输入数字", trigger: "blur" },
  ],
  type: [{ required: true, message: "请选择宿舍类型", trigger: "change" }],
  class_id: [{ required: true, message: "请选择班级", trigger: "change" }],
  program_id: [
    { required: true, message: "专业信息未自动关联", trigger: "change" },
  ],
  person_number: [
    { required: true, message: "请输入人数", trigger: "blur" },
    {
      type: "number",
      min: 0,
      max: 10,
      message: "人数范围0-10",
      trigger: "blur",
    },
  ],
  teacher: [
    { required: true, message: "请选择宿舍负责老师", trigger: "change" },
  ],
  comment: [{ max: 100, message: "备注最多100个字符", trigger: "blur" }],
});

// 新增数据的按钮
const showAddDrawer = () => {
  currentAction.value = "add";
  Object.assign(currentHostel, {
    id: undefined, // 添加ID字段用于编辑
    building_id: "",
    room_id: "",
    type: undefined,
    class_id: undefined,
    program_id: undefined,
    person_number: 0,
    teacher: "",
    comment: "",
  });
  drawerVisible.value = true;
};
// 添加表单引用
const formRef = ref();
// 根据传过来的班级id去找对应的专业---后端
const handleStudentSelect = async (class_id: number) => {
  console.log(class_id);
  try {
    const res = await http.get("/api/hostels/clsToprm", {
      params: {
        class_id: class_id,
      },
    });
    currentHostel.program_id = res.data.results[0].programs_id;
    console.log(res);
  } catch (error) {
    console.log("数据请求失败", error);
  }
};
// 重置表单数据
const resetForm = () => {
  Object.assign(currentHostel, {
    id: undefined,
    building_id: "",
    room_id: "",
    type: undefined,
    class_id: undefined,
    program_id: undefined,
    person_number: 0,
    teacher: "",
    comment: "",
  });
  // currentAction.value = "add";
};
// 提交表单的按钮
// 提交表单（添加/编辑）
const handleSubmit = async () => {
  try {
    // 执行表单验证
    await formRef.value.validate();
    // 构造请求参数
    const params = {
      // id, building_id, room_id, type, class_id, person_number, teacher, comment
      id: currentHostel.id, // 编辑时需要
      building_id: currentHostel.building_id,
      room_id: currentHostel.room_id,
      type: currentHostel.type,
      class_id: currentHostel.class_id,
      program_id: currentHostel.program_id,
      person_number: currentHostel.person_number,
      teacher: currentHostel.teacher,
      comment: currentHostel.comment,
    };

    // 根据操作类型调用不同接口
    if (currentAction.value === "add") {
      await http.post("/api/hostels/add", params);
      message.success("添加成功");
    } else {
      await http.post("/api/hostels/set", params);
      message.success("修改成功");
    }

    // 关闭抽屉并重置
    drawerVisible.value = false;
    resetForm();
    search_data(); // 刷新表格数据
  } catch (error) {
    message.error("操作失败");
  }
};
// 编辑操作需要添加的方法（在表格操作列调用）
const showEditDrawer = async (record: any) => {
  currentAction.value = "edit";
  Object.assign(currentHostel, record);
  drawerVisible.value = true;
  console.log(record);
};

/* 区3：表格数据操作 */
// 类型定义
interface AttendanceRecord {
  id?: number;
  studentName: string;
  student_id: number;
  className: string;
  programName: string;
  status: string;
  score: number;
  date: string;
  remark: string;
}
// 表格列定义
const columns = [
  {
    title: "ID",
    dataIndex: "id",
    key: "id",
  },
  {
    title: "楼栋号",
    dataIndex: "building_id",
    key: "building_id",
  },
  {
    title: "房间号",
    dataIndex: "room_id",
    key: "room_id",
  },
  {
    title: "宿舍类型",
    dataIndex: "type",
    key: "type",
  },
  {
    title: "班级",
    dataIndex: "class_name",
    key: "class_name",
  },
  {
    title: "专业",
    dataIndex: "program_name",
    key: "program_name",
  },
  {
    title: "人数",
    dataIndex: "person_number",
    key: "person_number",
  },
  {
    title: "负责老师",
    dataIndex: "teacher_name",
    key: "teacher_name",
  },
  {
    title: "状态",
    dataIndex: "state_del",
    key: "state_del",
  },
  {
    title: "联系方式",
    dataIndex: "teacher_phone",
    key: "teacher_phone",
  },
  {
    title: "备注",
    dataIndex: "comment",
    key: "comment",
  },
  {
    title: "操作",
    key: "action",
  },
];

// 响应式数据
const dataSource = ref<any[]>([]);
const loading = ref(false);
const pagination = reactive({
  current: 1,
  pageSize: 5,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ["5", "10", "20"],
  showTotal: (total: number) => `共 ${total} 条`,
});

// 加载数据
const loadData = async () => {
  try {
    loading.value = true;

    const response = await http.get("/api/hostels/list", {
      params: {
        page: pagination.current,
        page_size: pagination.pageSize,
        room_id: room_id.value,
        building_id: building_id.value,
        class_id: class_id.value,
        type: type.value,
      },
    });
    console.log(response);
    dataSource.value = response.data.results.assignments;
    pagination.total = response.data.results.total[0].count;
  } catch (error) {
    console.log(error);
    message.error("数据加载失败");
  } finally {
    loading.value = false;
  }
};
// 表格变化处理
const handleTableChange = (pag: any, filters: any, sorter: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
};
// 删除按钮handleDelete_f
const handleDelete_f = async (record: any) => {
  try {
    await http.get("/api/hostels/del_f", {
      params: {
        id: record.id,
      },
    });
    message.success("删除成功");
    loadData(); // 刷新数据
  } catch (error) {
    message.error("删除失败");
  }
};
const handleStart = async (record: any) => {
  try {
    await http.get("/api/hostels/start", {
      params: {
        id: record.id,
      },
    });
    message.success("删除成功");
    loadData(); // 刷新数据
  } catch (error) {
    message.error("删除失败");
  }
};
const handleDelete = async (record: any) => {
  try {
    await http.get("/api/hostels/del_t", {
      params: {
        id: record.id,
      },
    });
    message.success("删除成功");
    loadData(); // 刷新数据
  } catch (error) {
    message.error("删除失败");
  }
};
// 查看详情按钮
const open_view = ref<boolean>(false);
const view_data = reactive({
  room_id: undefined,
  building_id: undefined,
  type: "",
  person_number: undefined,
  class_name: "",
  program_name: "",
  teacher: "",
  teacher_phone: "",
  comment: "",
  floor: 0,
  bedCount: 6,
  availableBeds: 0, // 空位
});
// 查看详情赋值
const hostelView = async (record: any) => {
  open_view.value = true;
  try {
    const res = await http.get("/api/hostels/get", {
      params: {
        id: record.id,
      },
    });
    console.log(res);
    //     building_id: 1
    // class_id: 1
    // class_name: "软件2302"
    // comment: "宿舍住暂时住了1个的人--new"
    // person_number: 1
    // program_name: "软件工程"
    // room_id: 104
    // teacher: "萧火火"
    // teacher_phone: "13262623238"
    // type: "男生宿舍"
    view_data.building_id = res.data.results[0].building_id;
    view_data.class_name = res.data.results[0].class_name;
    view_data.person_number = res.data.results[0].person_number;
    view_data.type = res.data.results[0].type;
    view_data.teacher = res.data.results[0].teacher;
    view_data.teacher_phone = res.data.results[0].teacher_phone;
    view_data.room_id = res.data.results[0].room_id;
    view_data.program_name = res.data.results[0].program_name;
    view_data.comment = res.data.results[0].comment;
    view_data.availableBeds = 6 - Number(res.data.results[0].person_number);
    view_data.floor = parseInt(res.data.results[0].room_id.toString()[0], 10);
  } catch (error) {
    console.log("请求失败", error);
  }
};
// 确定按钮
const handleOk = () => {
  open_view.value = false;
};
// 取消按钮
const handleCancel = () => {
  open_view.value = false;
};

// 成员管理最后成员管理表--操作
// 变量声明
const drawerManage = ref<boolean>(false);
const detailData = reactive([
  {
    label: "房间号",
    value: 101,
  },
  {
    label: "楼栋号",
    value: 1,
  },
  {
    label: "班级",
    value: "",
  },
  {
    label: "专业",
    value: "",
  },
  {
    label: "班主任",
    value: "",
  },
]);
// 管理表格的表头部分
const columns_M = [
  {
    title: "学号",
    dataIndex: "student_id",
    key: "student_id",
  },
  {
    title: "姓名",
    dataIndex: "student_name",
    key: "student_name",
  },
  {
    title: "性别",
    dataIndex: "student_gender",
    key: "student_gender",
  },
  {
    title: "班级",
    dataIndex: "class_name",
    key: "class_name",
  },
  {
    title: "联系电话",
    dataIndex: "student_phone",
    key: "student_phone",
  },
  {
    title: "床位号",
    dataIndex: "bed_space",
    key: "bed_space",
  },
  {
    title: "操作",
    dataIndex: "active",
    key: "active",
  },
];
const hostel_id_M = ref<number>(); // 宿舍管理的id
const class_id_M = ref<number>(0); // 宿舍管理的班级id
const Number_hostel = ref(0);
// 表格中数据
const dataSource_M = ref<any[]>([]);
const pagination_M = reactive({
  current: 1,
  pageSize: 5,
  total: 0,
  // showSizeChanger: true,
  // pageSizeOptions: ["5", "10", "20"],
  showTotal: (total: number) => `共 ${total} 条`,
});
/* 方法操作 */
// 加载学生数据
const loadStudent_of = async (class_id: number) => {
  try {
    const res = await http.get("/api/attends/allStudent", {
      params: {
        class_id: class_id,
      },
    });
    all_studentList.value = res.data.results;
    console.log(res.data.results);
  } catch (error) {
    message.error("专业数据加载失败-学生");
  }
};
// 打开抽屉
const manage = (record: any) => {
  drawerManage.value = true;
  console.log(record);
  detailData[0].value = record.room_id;
  detailData[1].value = record.building_id;
  detailData[2].value = record.class_name;
  detailData[3].value = record.program_name;
  detailData[4].value = record.teacher;
  hostel_id_M.value = record.id;
  class_id_M.value = record.class_id;
  loadDataM();
};
// 加载数据
const loadDataM = async () => {
  try {
    const res = await http.get("/api/hostels/person_list", {
      params: {
        hostel_id: hostel_id_M.value,
        page: pagination_M.current,
        page_size: pagination_M.pageSize,
      },
    });
    console.log(res);
    dataSource_M.value = res.data.results.list;
    pagination_M.total = res.data.results.total[0].total;
    Number_hostel.value = res.data.results.total[0].total;
  } catch (error) {
    console.log("数据加载失败", error);
  }
};
// 表格变化处理
const handleTableChange_M = (pag: any, filters: any, sorter: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
};
// 宿舍成员的编辑
const showEditDrawerM = (record: any) => {
  console.log(record);
  currentAction_M.value = "edit";
  console.log(currentAction_M.value);
  currentHostelM.id = record.id;
  currentHostelM.student_idOF = record.studentid;
  currentHostelM.student_id = record.student_id;
  currentHostelM.class_id = record.class_name;
  currentHostelM.gender = record.student_gender;
  currentHostelM.phone = record.student_phone;
  currentHostelM.bed_space = record.bed_space;
  open_Add.value = true;
  loadStudent_of(class_id_M.value);
};
// 宿舍成员的删除
const handleDeleteM = async (record: any) => {
  Modal.confirm({
    title: "确认删除",
    content: `确定要删除 ${record.student_name} 的宿舍分配记录吗？`,
    okText: "确认删除",
    okType: "danger",
    cancelText: "取消",
    centered: true,
    async onOk() {
      try {
        const res = await http.get("/api/hostels/person_del_f", {
          params: { id: record.id, hostel_id: hostel_id_M.value },
        });

        message.success("已成功移除该宿舍成员");
        // 刷新数据列表
        loadDataM();
        loadData();
        console.log(res);
      } catch (error: any) {
        Modal.error({
          title: "删除失败",
          content: `操作未能完成：${error.message}`,
          okText: "重新尝试",
        });
        console.error("删除失败:", error);
      }
    },
    onCancel() {
      console.log("用户取消了删除操作");
    },
  });
};
// 进度条内容自定义函数
const changeData = (percent: number) => {
  return `${Number_hostel.value}/4`;
};

/* 添加宿舍中的学生 */
// 定义响应式数据
const formRefM = ref();
const open_Add = ref<boolean>(false);
const currentAction_M = ref<"add" | "edit">("add");
const currentHostelM = reactive({
  id: undefined, // 添加ID字段用于编辑
  studentid: undefined,
  student_idOF: undefined,
  student_name: "",
  student_id: undefined,
  class_id: undefined,
  gender: undefined,
  phone: "",
  bed_space: "",
});
// 验证规则
const formRulesM = reactive({
  student_idOF: [
    {
      required: true,
      message: "请选择学生姓名",
      trigger: ["change", "blur"],
    },
  ],

  // 学号验证（自动填充）
  student_id: [
    {
      required: true,
      message: "学号不能为空",
      trigger: ["change", "submit"],
    },
  ],

  // 性别单选验证
  gender: [
    {
      required: true,
      message: "请选择性别",
      trigger: ["change", "blur"],
    },
  ],

  // 班级选择验证
  class_id: [
    {
      required: true,
      message: "请选择所属班级",
      trigger: ["change", "blur"],
    },
  ],

  // 手机号格式验证
  phone: [
    {
      required: true,
      message: "请输入联系电话",
      trigger: "blur",
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入有效的11位手机号",
      trigger: ["blur", "submit"],
    },
  ],

  // 床位号范围验证
  bed_space: [
    {
      required: true,
      message: "请输入床位编号",
      trigger: "blur",
    },
    {
      type: "integer",
      min: 0,
      max: 4,
      message: "请输入0-4之间的整数",
      trigger: ["blur", "change"],
    },
  ],
});

// 添加按钮
const showAddDrawer_M = () => {
  currentAction_M.value = "add";
  console.log(currentAction_M.value, Number_hostel.value, typeof Number_hostel);
  open_Add.value = true;
  loadStudent_of(class_id_M.value);
};

// 根据学生名字去找学生号
const handleStudentSelect_M = async (student_id: number) => {
  console.log("选中学生ID:", student_id);
  // 执行相关操作，如加载学生详情
  try {
    const res = await http.get("/api/attends/ToStudentid", {
      params: {
        student_id: student_id,
      },
    });
    currentHostelM.student_id = res.data.results[0].student_id;
    currentHostelM.class_id = res.data.results[0].class_name;
    currentHostelM.phone = res.data.results[0].phone;
    currentHostelM.gender = res.data.results[0].gender;
    // currentHostelM.gender
    console.log(res);
  } catch (error) {
    console.log("数据请求失败", error);
  }
};

// 添加Model中的确定按钮-提交按钮
// 重置
const reset_m = () => {
  Object.assign(currentHostelM, {
    id: undefined,
    student_id: undefined,
    student_idOF: undefined,
    student_name: "",
    class_id: undefined,
    gender: undefined,
    phone: "",
    building: "", // 新增楼栋字段
    room_number: "", // 新增房间号
    bed_space: "",
    check_in_date: null, // 日期字段建议用null
  });
};
const handleOk_M = async () => {
  await formRefM.value.validateFields();
  try {
    if (currentAction_M.value === "add") {
      await http.post("/api/hostels/person_add", {
        hostel_id: hostel_id_M.value,
        student_id: currentHostelM.student_idOF,
        bed_space: currentHostelM.bed_space,
      });
      console.log(1);
    }
    if (currentAction_M.value === "edit") {
      await http.post("/api/hostels/person_set", {
        id: currentHostelM.id,
        hostel_id: hostel_id_M.value,
        student_id: currentHostelM.student_idOF,
        bed_space: currentHostelM.bed_space,
      });
      console.log(2);
    }
    message.success("操作成功");
    open_Add.value = false;
    loadDataM();
    loadData();
    reset_m();
    // 提交逻辑...
  } catch (e) {
    message.error("操作失败");
    console.error("表单校验失败:", e);
  }
};
// 添加Model中的取消按钮
const handleCancel_M = () => {
  open_Add.value = false;
};
</script>
<style scoped>
.action-buttons {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 0;
  width: 24px;
  height: 24px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s;
}

.action-btn:hover {
  background-color: rgba(0, 0, 0, 0.06);
}

.edit-btn {
  color: #52c41a;
}

.enable-btn {
  color: #52c41a;
}

.disable-btn {
  color: #ff4d4f;
}

.delete-btn {
  color: #ff4d4f;
}

.detail-btn {
  color: #91959c;
}

.manage-btn {
  color: #fa8c16;
}
</style>
<style scoped>
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > .anticon + span),
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > span + .anticon) {
  margin-inline-start: 0px;
}
.dorm-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.header {
  color: #333;
  border-bottom: 2px solid #eee;
  padding-bottom: 12px;
  margin-bottom: 15px;
  font-size: 18px;
}

.info-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 25px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  padding: 6px 0;
  border-bottom: 1px solid #f5f5f5;
}

.label {
  color: #666;
  font-size: 14px;
}

.value {
  color: #333;
  font-weight: 500;
}

.remark-box {
  margin-top: 15px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #eee;
}

.remark-label {
  color: #888;
  font-size: 13px;
  margin-bottom: 6px;
}

.remark-content {
  color: #e65c5c;
  font-size: 14px;
  line-height: 1.4;
}

.activeAdd {
  display: flex;
  justify-content: space-between;
}
</style>